<template>
  <div class="app-container">
    <div style="margin-bottom: 10px;">
      <el-input v-model="queryParams.itemCode" placeholder="请输入物料编码"
                style="width: 200px; margin-right: 10px;"></el-input>
      <el-input v-model="queryParams.itemName" placeholder="请输入物料名称"
                style="width: 200px; margin-right: 10px;"></el-input>
      <!-- 新增库存状态查询下拉框 -->
      <el-select v-model="queryParams.stockStatus" placeholder="请选择库存状态" clearable
                 style="width: 150px; margin-right: 10px;">
        <el-option label="全部" value=""></el-option>
        <el-option label="一致" value="consistent"></el-option>
        <el-option label="不一致" value="inconsistent"></el-option>
      </el-select>
      <el-button type="primary" @click="globalSearch">查询</el-button>
      <el-button @click="resetSearch">重置</el-button>
    </div>
    <div style="margin-bottom: 10px;">
      <el-button v-for="warehouse in warehouses" :key="warehouse"
                 :type="selectedWarehouse === warehouse ? 'primary' : 'default'" @click="selectWarehouse(warehouse)"
                 style="margin-right: 5px;">
        {{ warehouse }}
      </el-button>
      <!-- 为每个仓库添加单独的导出按钮 -->
      <el-dropdown @command="exportByWarehouse" style="margin-left: 10px;">
        <el-button type="success">
          导出<i class="el-icon-arrow-down el-icon--right"></i>
        </el-button>
        <el-dropdown-menu slot="dropdown">
          <el-dropdown-item v-for="warehouse in warehouses" :key="warehouse" :command="warehouse">
            导出{{ warehouse }}
          </el-dropdown-item>
        </el-dropdown-menu>
      </el-dropdown>
      <!-- 导出当前仓库按钮 -->
      <el-button v-hasPermi="['mes:reco:repo:export']" type="success" @click="handleExport" style="margin-left: 10px;"
                 :loading="exportLoading">
        导出当前
      </el-button>
    </div>
    <el-button v-hasPermi="['mes:reco:repo:summary']" type="primary" @click="syncData" style="margin-bottom: 10px;">
      同步数据
    </el-button>
    <el-button v-hasPermi="['mes:reco:repo:repoSummaryReal']" type="primary" @click="syncRealData" style="margin-bottom: 10px;">
      同步实时库存数据
    </el-button>
    <el-table :data="tableData" style="width: 100%" @sort-change="handleSortChange" :loading="loading"
              :row-style="getRowStyle">
      <el-table-column prop="itemName" align="center" label="物料名称"></el-table-column>
      <el-table-column prop="itemCode" align="center" label="物料编码"></el-table-column>
      <el-table-column prop="itemSpec" align="center" label="规格"></el-table-column>
      <el-table-column prop="itemWare" align="center" label="仓库">
        <template slot-scope="scope">
          <span v-if="selectedWarehouse === '云仓'">{{ scope.row.displayWare || scope.row.itemWare || '未分配' }}</span>
          <span v-else-if="selectedWarehouse === '次品仓'">{{ scope.row.itemWare || '未分配' }}</span>
          <span v-else>{{ scope.row.itemWare }}</span>
        </template>
      </el-table-column>
      <el-table-column prop="inQty" align="center" label="入库数量" sortable="custom"></el-table-column>
      <el-table-column prop="outQty" align="center" label="出库数量" sortable="custom"></el-table-column>
      <el-table-column prop="realStock" align="center" label="实时库存" sortable="custom">
        <template slot-scope="scope">
          <span :class="getStockClass(scope.row)">{{ scope.row.realStock }}</span>
        </template>
      </el-table-column>
      <!-- 对账库存列：云仓不显示 -->
      <el-table-column v-if="selectedWarehouse !== '云仓'" prop="recoStock" align="center" label="对账库存" sortable="custom">
        <template slot-scope="scope">
          <span :class="getStockClass(scope.row)">{{ scope.row.recoStock }}</span>
        </template>
      </el-table-column>
      <!-- 库存状态列：云仓不显示 -->
      <el-table-column v-if="selectedWarehouse !== '云仓'" label="库存状态" align="center">
        <template slot-scope="scope">
          <el-tag v-if="isStockInconsistent(scope.row)" type="danger">不一致</el-tag>
          <el-tag v-else type="success">一致</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="操作">
        <template slot-scope="scope">
          <el-button type="text" @click="showDetails(scope.row.itemCode)">详情</el-button>
          <!-- 发送通知按钮：云仓不显示 -->
          <el-button v-if="selectedWarehouse !== '云仓' && isStockInconsistent(scope.row)" type="text"
                     @click="sendDingTalkNotification(scope.row.itemCode)" style="color: #ff4949;">
            发送通知
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 详情对话框 -->
    <el-dialog :visible.sync="dialogVisible" title="出入库详情" width="80%">
      <div v-if="itemDetails">
        <h3>入库详情</h3>
        <el-table :data="itemDetails.inDetails.concat([summaryRowIn])" style="width: 100%" max-height="250">
          <el-table-column prop="recptEntryNum" label="入库单编号"></el-table-column>
          <el-table-column prop="invenMaterialName" label="物料名称"></el-table-column>
          <el-table-column prop="invenMaterialNum" label="物料编码"></el-table-column>
          <el-table-column prop="receiveGoodQuantity" label="入库数量">
            <template slot-scope="scope">
              <span v-if="scope.row.receiveGoodQuantity !== undefined">{{ scope.row.receiveGoodQuantity }}</span>
              <strong v-else>汇总: {{ summaryData.totalInQty }}</strong>
            </template>
          </el-table-column>
          <el-table-column prop="warehouseTime" label="入库时间">
            <template slot-scope="scope">
              {{ formatDateTime(scope.row.warehouseTime) }}
            </template>
          </el-table-column>
        </el-table>

        <hr>
        <h3>出库详情</h3>
        <el-table :data="itemDetails.outDetails.concat([summaryRowOut])" style="width: 100%" max-height="250">
          <el-table-column prop="serialNumber" label="出库单编号"></el-table-column>
          <el-table-column prop="issueMaterialName" label="物料名称"></el-table-column>
          <el-table-column prop="issueMaterialCode" label="物料编码"></el-table-column>
          <el-table-column prop="issueOutboundQuantity" label="出库数量">
            <template slot-scope="scope">
              <span v-if="scope.row.issueOutboundQuantity !== undefined">{{ scope.row.issueOutboundQuantity }}</span>
              <strong v-else>汇总: {{ summaryData.totalOutQty }}</strong>
            </template>
          </el-table-column>
          <el-table-column prop="confirmDeliveryTime" label="出库时间">
            <template slot-scope="scope">
              {{ formatDateTime(scope.row.confirmDeliveryTime) }}
            </template>
          </el-table-column>
        </el-table>

        <hr>
        <h3>对账详情</h3>
        <el-table :data="itemDetails.recoDetails.concat([summaryRowReco])" style="width: 100%" max-height="250">
          <el-table-column prop="recoCode" label="对账编号"></el-table-column>
          <el-table-column prop="itemName" label="物料名称"></el-table-column>
          <el-table-column prop="itemCode" label="物料编码"></el-table-column>
          <el-table-column prop="itemNum" label="出/入库数量">
            <template slot-scope="scope">
              <span v-if="scope.row.itemNum !== undefined">{{ scope.row.itemNum }}</span>
              <strong v-else>汇总: {{ summaryData.totalRecoDiff }}</strong>
            </template>
          </el-table-column>
          <el-table-column prop="itemCondition" label="出/入库"></el-table-column>
          <el-table-column prop="storageTime" label="出/入库日期">
            <template slot-scope="scope">
              {{ formatDateTime(scope.row.storageTime) }}
            </template>
          </el-table-column>
          <el-table-column prop="recoStatus" label="状态"></el-table-column>
        </el-table>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">关闭</el-button>
      </span>
    </el-dialog>
    <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange"
                   :current-page="queryParams.pageNum" :page-sizes="[10, 20, 30, 40]" :page-size="queryParams.pageSize"
                   layout="total, sizes, prev, pager, next, jumper" :total="total" style="margin-top: 10px;">
    </el-pagination>
  </div>
</template>

<script>
import {
  repoSummary,
  getdefectiveData,
  getProductsData,
  getItemData,
  getConsumablesData,
  getpackageItemData,
  getSampleData,
  getItemInDetail,
  getItemOutDetail,
  getItemRecoDetail,
  searchItem,
  repoSummaryReal,
  ycInventory // 添加云仓数据获取方法
} from '@/api/mes/reco/recopivottable';
import {
  download
} from '@/utils/request'; // 引入下载工具
import request from '@/utils/request';

export default {
  data() {
    return {
      tableData: [],
      loading: false,
      exportLoading: false,
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        warehouseName: '',
        itemCode: '',
        itemName: '',
        stockStatus: '', // 新增库存状态查询参数
        sortField: '',
        sortOrder: ''
      },
      total: 0,
      selectedWarehouse: '',
      // 在仓库列表中添加"云仓"
      warehouses: ['半/成品库', '主/辅料库', '易耗品库', '包材库', '样品库', '次品仓', '云仓'],
      dialogVisible: false,
      itemDetails: null,
      summaryData: {
        totalInQty: 0,
        totalOutQty: 0,
        totalRecoDiff: 0
      },
      summaryRowIn: {},
      summaryRowOut: {},
      summaryRowReco: {},
      warehouseMap: {
        '常温-成品仓': '半/成品库',
        '速冻-成品仓': '半/成品库',
        '速冻-半成品仓': '半/成品库',
        '常温-半成品仓': '半/成品库',
        '常温-辅料仓': '主/辅料库',
        '速冻-辅料仓': '主/辅料库',
        '常温-主料仓': '主/辅料库',
        '速冻-主料仓': '主/辅料库',
        '添加剂仓': '主/辅料库',
        '常温-包材仓': '包材库',
        '速冻-包材仓': '包材库',
        '包材公共仓': '包材库',
        '常温-样品仓': '样品库',
        '速冻-样品仓': '样品库',
        '次品库': '次品仓',
        '易耗品仓': '易耗品库'
        // 云仓不需要映射
      }
    };
  },
  methods: {
    // 判断库存是否不一致
    isStockInconsistent(row) {
      if (row.realStock === undefined || row.recoStock === undefined) {
        return false;
      }
      return row.realStock !== row.recoStock;
    },
    // 重置搜索方法
    resetSearch() {
      this.queryParams.itemCode = '';
      this.queryParams.itemName = '';
      this.queryParams.stockStatus = '';
      this.fetchData();
    },

    // 获取库存显示样式
    getStockClass(row) {
      return {
        'stock-inconsistent': this.isStockInconsistent(row)
      };
    },

    // 发送钉钉通知
    sendDingTalkNotification(itemCode) {
      this.$confirm('确定要发送库存不一致通知到钉钉群吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        request({
          url: 'mes/reco/ckdz/sendItemRepoInfoToDingTalk',
          method: 'get',
          params: {
            itemCode
          }
        }).then(response => {
          if (response.code === 200) {
            this.$message.success(response.msg || '发送成功');
          } else {
            this.$message.error(response.msg || '发送失败');
          }
        }).catch(error => {
          this.$message.error('发送失败: ' + error.message);
        });
      }).catch(() => {
        this.$message.info('已取消发送');
      });
    },

    // 云仓搜索
    searchYcInventory() {
      const { itemCode, itemName } = this.queryParams;
      this.loading = true;

      // 构造查询参数
      const params = {
        pageNum: undefined,
        pageSize: undefined
      };

      if (itemCode) params.itemCode = itemCode;
      if (itemName) params.itemName = itemName;

      ycInventory(params)
        .then(response => {
          // 处理云仓数据
          let data = [];
          if (response.rows && Array.isArray(response.rows)) {
            data = [...response.rows];
          } else if (response.data && Array.isArray(response.data)) {
            data = [...response.data];
          } else if (Array.isArray(response)) {
            data = [...response];
          }

          // 云仓数据处理逻辑
          data = data.map(item => {
            if (item.itemWare) {
              const matchedKey = Object.keys(this.warehouseMap).find(key => item.itemWare.includes(key));
              if (matchedKey) {
                item.displayWare = this.warehouseMap[matchedKey];
              } else {
                item.displayWare = item.itemWare;
              }
            } else {
              item.displayWare = '未分配';
            }
            return item;
          });

          this.total = data.length;
          const start = (this.queryParams.pageNum - 1) * this.queryParams.pageSize;
          const end = start + this.queryParams.pageSize;
          this.tableData = data.slice(start, end);
        })
        .catch(error => {
          console.error('云仓查询失败:', error);
          this.$message.error('云仓查询失败: ' + error.message);
        })
        .finally(() => {
          this.loading = false;
        });
    },

    // 次品仓搜索
    searchDefectiveInventory() {
      const { itemCode, itemName } = this.queryParams;
      this.loading = true;

      // 构造查询参数
      const params = {
        pageNum: undefined,
        pageSize: undefined
      };

      if (itemCode) params.itemCode = itemCode;
      if (itemName) params.itemName = itemName;

      request({
        url: '/mes/reco/repo/defectiveInventory',
        method: 'get',
        params: params
      })
        .then(response => {
          // 处理次品仓数据
          let data = [];
          if (response.rows && Array.isArray(response.rows)) {
            data = [...response.rows];
          } else if (response.data && Array.isArray(response.data)) {
            data = [...response.data];
          } else if (Array.isArray(response)) {
            data = [...response];
          }

          this.total = data.length;
          const start = (this.queryParams.pageNum - 1) * this.queryParams.pageSize;
          const end = start + this.queryParams.pageSize;
          this.tableData = data.slice(start, end);
        })
        .catch(error => {
          console.error('次品仓查询失败:', error);
          this.$message.error('次品仓查询失败: ' + error.message);
        })
        .finally(() => {
          this.loading = false;
        });
    },

    globalSearch() {
      const {
        itemCode,
        itemName
      } = this.queryParams;

      // 如果输入了物料编码或物料名称，则使用对应仓库的搜索接口进行查询
      if (itemCode || itemName) {
        this.loading = true;

        // 根据当前选中的仓库类型执行不同的搜索逻辑
        if (this.selectedWarehouse === '云仓') {
          this.searchYcInventory();
        } else if (this.selectedWarehouse === '次品仓') {
          this.searchDefectiveInventory();
        } else {
          searchItem({
            itemCode,
            itemName
          })
            .then(response => {
              const warehouse = response.warehouse;

              // 自动选择对应的仓库
              const matchedKey = Object.keys(this.warehouseMap).find(key => warehouse.includes(key));
              const matchedWarehouse = matchedKey ? this.warehouseMap[matchedKey] : null;

              if (matchedWarehouse) {
                this.selectedWarehouse = matchedWarehouse;
                this.queryParams.warehouseName = matchedWarehouse;
                this.fetchData();
              } else {
                this.$message.error('未找到对应仓库');
              }
            })
            .catch(() => {
              this.$message.error('未找到对应物料');
            })
            .finally(() => {
              this.loading = false;
            });
        }
      } else {
        // 如果没有输入物料编码或物料名称，则直接查询当前选中仓库的数据
        this.fetchData();
      }
    },
    fetchData() {
      this.loading = true;

      // 创建一个不带分页参数的查询参数对象
      const queryWithoutPagination = {
        ...this.queryParams,
        pageNum: undefined,
        pageSize: undefined
      };

      let fetchDataPromise;

      if (!this.selectedWarehouse || this.selectedWarehouse === '') {
        fetchDataPromise = repoSummary(queryWithoutPagination);
      } else {
        // 添加云仓和次品仓数据获取逻辑
        if (this.selectedWarehouse === '云仓') {
          fetchDataPromise = ycInventory(queryWithoutPagination);
        } else if (this.selectedWarehouse === '次品仓') {
          fetchDataPromise = request({
            url: '/mes/reco/repo/defectiveInventory',
            method: 'get',
            params: queryWithoutPagination
          });
        } else {
          switch (this.selectedWarehouse) {
            case '半/成品库':
              fetchDataPromise = getProductsData(queryWithoutPagination);
              break;
            case '主/辅料库':
              fetchDataPromise = getItemData(queryWithoutPagination);
              break;
            case '易耗品库':
              fetchDataPromise = getConsumablesData(queryWithoutPagination);
              break;
            case '包材库':
              fetchDataPromise = getpackageItemData(queryWithoutPagination);
              break;
            case '样品库':
              fetchDataPromise = getSampleData(queryWithoutPagination);
              break;
            default:
              fetchDataPromise = Promise.resolve({
                code: 200,
                rows: [],
                total: 0
              });
          }
        }
      }

      fetchDataPromise
        .then(response => {
          // 修复数据处理逻辑 - 确保正确获取数据
          let data = [];
          if (response.rows && Array.isArray(response.rows)) {
            data = [...response.rows];
          } else if (response.data && Array.isArray(response.data)) {
            data = [...response.data];
          } else if (Array.isArray(response)) {
            data = [...response];
          }

          // console.log('获取到的数据:', response);
          // console.log('处理后的数据数组:', data);

          // 特殊处理云仓和次品仓数据 - 显示所有数据，不需要过滤
          if (this.selectedWarehouse === '云仓' || this.selectedWarehouse === '次品仓') {
            // console.log(`处理${this.selectedWarehouse}数据，原始数据:`, data);
            // 对于云仓，不需要根据itemWare过滤，显示所有获取到的数据
            if (this.selectedWarehouse === '云仓') {
              data = data.map(item => {
                // 如果需要，可以映射itemWare到前端显示的仓库名称
                if (item.itemWare) {
                  const matchedKey = Object.keys(this.warehouseMap).find(key => item.itemWare.includes(key));
                  if (matchedKey) {
                    item.displayWare = this.warehouseMap[matchedKey]; // 添加一个用于显示的字段
                  } else {
                    item.displayWare = item.itemWare; // 如果没有匹配则直接显示原始仓库名
                  }
                } else {
                  item.displayWare = '未分配';
                }
                return item;
              });
            }
            // console.log(`处理后的${this.selectedWarehouse}数据:`, data);
          }

          // 根据库存状态筛选数据
          if (this.queryParams.stockStatus && this.selectedWarehouse !== '云仓') {
            if (this.queryParams.stockStatus === 'consistent') {
              data = data.filter(row => !this.isStockInconsistent(row));
            } else if (this.queryParams.stockStatus === 'inconsistent') {
              data = data.filter(row => this.isStockInconsistent(row));
            }
          }

          // 优先按库存一致性排序：不一致的放在前面
          if (this.selectedWarehouse !== '云仓') {
            data.sort((a, b) => {
              const aInconsistent = this.isStockInconsistent(a) ? 0 : 1;
              const bInconsistent = this.isStockInconsistent(b) ? 0 : 1;
              return aInconsistent - bInconsistent;
            });
          }

          // 前端实现其他排序
          if (this.queryParams.sortField && this.queryParams.sortOrder) {
            const { sortField, sortOrder } = this.queryParams;
            data.sort((a, b) => {
              if (a[sortField] > b[sortField]) return sortOrder === 'asc' ? 1 : -1;
              if (a[sortField] < b[sortField]) return sortOrder === 'asc' ? -1 : 1;
              return 0;
            });
          }

          // 前端实现分页
          this.total = data.length;
          const start = (this.queryParams.pageNum - 1) * this.queryParams.pageSize;
          const end = start + this.queryParams.pageSize;
          this.tableData = data.slice(start, end);
          // console.log('最终显示的数据:', this.tableData);
        })
        .catch(error => {
          console.error('查询失败:', error);
          this.$message.error('查询失败: ' + error.message);
        })
        .finally(() => {
          this.loading = false;
        });
    },
    selectWarehouse(warehouse) {
      this.selectedWarehouse = warehouse;
      this.queryParams.warehouseName = warehouse;
      this.fetchData();
    },
    syncData() {
      this.$confirm('确定要同步数据吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        const loadingInstance = this.$loading({
          fullscreen: true,
          text: '数据同步中，请稍候...',
          spinner: 'el-icon-loading',
          background: 'rgba(0, 0, 0, 0.3)'
        });

        repoSummary(this.queryParams)
          .then(response => {
            this.$message.success('数据同步成功');
            this.fetchData();
          })
          .catch(error => {
            console.error('同步数据时出现错误!', error);
            this.$message.error('数据同步失败');
          })
          .finally(() => {
            loadingInstance.close();
          });
      }).catch(() => {
        this.$message.info('已取消同步');
      });
    },
    syncRealData() {
      this.$confirm('确定要同步数据吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        const loadingInstance = this.$loading({
          fullscreen: true,
          text: '数据同步中，请稍候...',
          spinner: 'el-icon-loading',
          background: 'rgba(0, 0, 0, 0.3)'
        });

        repoSummaryReal(this.queryParams)
          .then(response => {
            this.$message.success('数据同步成功');
            this.fetchData();
          })
          .catch(error => {
            console.error('同步数据时出现错误!', error);
            this.$message.error('数据同步失败');
          })
          .finally(() => {
            loadingInstance.close();
          });
      }).catch(() => {
        this.$message.info('已取消同步');
      });
    },
    handleSizeChange(newSize) {
      this.queryParams.pageSize = newSize;
      this.fetchData();
    },
    handleCurrentChange(newPage) {
      this.queryParams.pageNum = newPage;
      this.fetchData();
    },
    showDetails(itemCode) {
      this.dialogVisible = true;
      this.fetchItemDetails(itemCode);
    },
    fetchItemDetails(itemCode) {
      Promise.all([
        getItemInDetail(itemCode),
        getItemOutDetail(itemCode),
        getItemRecoDetail(itemCode)
      ]).then(results => {
        const inDetails = results[0].data || [];
        const outDetails = results[1].data || [];
        const recoDetails = results[2].data || [];

        // 计算汇总数据
        const totalInQty = inDetails.reduce((acc, item) => acc + (item.receiveGoodQuantity || 0), 0);
        const totalOutQty = outDetails.reduce((acc, item) => acc + (item.issueOutboundQuantity || 0), 0);
        const totalRecoDiff = recoDetails.reduce((acc, item) => {
          if (item.itemCondition === '已入库') {
            return acc + (item.itemNum || 0);
          } else if (item.itemCondition === '已出库') {
            return acc - (item.itemNum || 0);
          }
          return acc;
        }, 0);

        this.itemDetails = {
          inDetails,
          outDetails,
          recoDetails
        };

        this.summaryData = {
          totalInQty,
          totalOutQty,
          totalRecoDiff
        };

        // 更新汇总行
        this.summaryRowIn = {
          receiveGoodQuantity: undefined
        };
        this.summaryRowOut = {
          issueOutboundQuantity: undefined
        };
        this.summaryRowReco = {
          itemNum: undefined
        };
      }).catch(error => {
        console.error('Error fetching item details:', error);
        this.$message.error('获取出入库详情失败');
      });
    },
    formatDateTime(date) {
      if (!date) return '';
      const d = new Date(date);
      const year = d.getFullYear();
      const month = String(d.getMonth() + 1).padStart(2, '0');
      const day = String(d.getDate()).padStart(2, '0');
      return `${year}-${month}-${day}`;
    },
    handleSortChange({
      column,
      prop,
      order
    }) {
      this.queryParams.sortField = prop;
      this.queryParams.sortOrder = order ? (order === 'ascending' ? 'asc' : 'desc') : '';
      this.fetchData();
    },
    getRowStyle({
      row
    }) {
      if (row.realStock === 0) {
        return {
          backgroundColor: '#fff3cd'
        };
      } else if (row.realStock > 0) {
        return {
          backgroundColor: '#d4edda'
        };
      } else if (row.realStock < 0) {
        return {
          backgroundColor: '#f8d7da'
        };
      }
      return {};
    },
    // 为特定仓库导出数据
    exportByWarehouse(warehouse) {
      const prevWarehouse = this.selectedWarehouse;
      this.selectedWarehouse = warehouse;
      this.queryParams.warehouseName = warehouse;
      this.handleExport();
      this.selectedWarehouse = prevWarehouse;
      this.queryParams.warehouseName = prevWarehouse;
    },
    // 导出当前仓库数据
    handleExport() {
      if (!this.selectedWarehouse) {
        this.$message.warning('请先选择一个仓库');
        return;
      }

      this.exportLoading = true;

      // 根据仓库类型确定导出接口路径
      let exportUrl = '';
      switch (this.selectedWarehouse) {
        case '半/成品库':
          exportUrl = 'mes/reco/ckdz/products/export';
          break;
        case '主/辅料库':
          exportUrl = 'mes/reco/ckdz/item/export';
          break;
        case '易耗品库':
          exportUrl = 'mes/reco/ckdz/consumables/export';
          break;
        case '包材库':
          exportUrl = 'mes/reco/ckdz/packageItem/export';
          break;
        case '样品库':
          exportUrl = 'mes/reco/ckdz/sample/export';
          break;
        case '次品仓':
          exportUrl = 'mes/reco/repo/defective/export'; // 次品仓导出接口
          break;
        case '云仓':
          exportUrl = 'mes/reco/ckdz/ycInventory/export'; // 云仓导出接口
          break;
        default:
          exportUrl = 'mes/reco/ckdz/repo/export';
      }

      // 调用后端导出接口
      download(exportUrl, {
        ...this.queryParams,
        pageNum: undefined,
        pageSize: undefined
      }, `${this.selectedWarehouse}库存数据_${this.getCurrentDate()}.xlsx`)
        .finally(() => {
          this.exportLoading = false;
        });
    },
    // 获取当前日期字符串
    getCurrentDate() {
      const now = new Date();
      const year = now.getFullYear();
      const month = String(now.getMonth() + 1).padStart(2, '0');
      const day = String(now.getDate()).padStart(2, '0');
      return `${year}${month}${day}`;
    }
  },
  created() {
    this.selectedWarehouse = '半/成品库';
    this.queryParams.warehouseName = '半/成品库';
    this.fetchData();
  }
};
</script>

<style scoped>
/* 库存不一致时的样式 */
.stock-inconsistent {
  color: #ff4949;
  font-weight: bold;
}
</style>
